package migrate

import (
	"context"

	"device-admin/config/mysql"
	"device-admin/internal/models"

	sharding "192.168.1.75/go-pkg/db-sharding"
	"192.168.1.75/go-pkg/logx"
	"gorm.io/gorm"
)

type MigrateFunc struct{}

// Script1
// 增加热力图Model,修改map model
func (MigrateFunc) Script2() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.AutoMigrate(&models.DeviceHeatMap{}, &models.DeviceMap{}, &models.DeviceActiveDuration{}, &models.Device{})
	return nil
}

// Script2
func (MigrateFunc) Script3() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	// 有关告警通知的优化
	{
		// 自动迁移
		tx.AutoMigrate(&models.AlarmNotifyRecord{})
		// 新增pos_direction字段，并用robot_direction初始化其值
		// 新增created_date字段，并用created_at初始化其值
		err := tx.Session(&gorm.Session{AllowGlobalUpdate: true}).
			Model(&models.AlarmNotifyRecord{}).
			Updates(map[string]interface{}{
				"pos_direction": gorm.Expr("robot_direction"),
				"created_date":  gorm.Expr("date_format(from_unixtime(created_at), '%Y-%m-%d')"),
			}).Error
		if err != nil {
			logx.Error(context.Background(), "Migrate003", logx.Err(err))
		}
	}
	// 商场品牌管理的优化
	{
		// 去除废弃的名称索引
		tx.Migrator().DropIndex(&models.Brand{}, "name")
		// 更新map为空的字段值为null
		tx.Model(&models.Floor{}).Where("map = ?", "").Updates(map[string]interface{}{
			"map": nil,
		})
		// 增加字段(enable_nav)
		tx.AutoMigrate(&models.Location{})
		// 增加唯一索引(name,location_id)
		tx.AutoMigrate(&models.Floor{})
		// 品牌表迁移,增加唯一索引（名称-位置），增加字段（位置）
		tx.AutoMigrate(&models.Brand{})
	}
	// 常规优化
	{
		// 设备活跃时长表迁移，增加唯一索引(robot_id,date),增加索引(created_at)
		tx.AutoMigrate(&models.DeviceActiveDuration{})
		// 设备日统计表迁移，增加唯一索引(merchant_id,name,date),增加索引(created_at)
		tx.AutoMigrate(&models.DeviceDailyReport{})
		// 增加索引(created_at),增加索引(robot_id,name,created_at)
		tx.AutoMigrate(&models.DeviceMetric{})
		// 增加索引(map_name),增加索引(robot_id),增加索引（map_md5）
		// 增加map_name的长度为100
		tx.AutoMigrate(&models.DeviceMap{})
		// 增加map_name的长度为100
		tx.AutoMigrate(&models.DeviceHeatMap{})
		tx.AutoMigrate(&models.Device{})
	}
	// 终端管理
	{
		tx.AutoMigrate(
			&models.Terminal{},
			&models.UpgradePackage{},
			&models.UpgradeSchedule{},
			&models.UpgradeTerminals{},
		)
		// 移除废弃的字段
		tx.Exec("ALTER TABLE upgrade_schedule DROP COLUMN exclude_robot_ids")
		tx.Exec("ALTER TABLE upgrade_schedule DROP COLUMN include_robot_ids")
		tx.Exec("ALTER TABLE upgrade_schedule DROP COLUMN include_terminal_type")
		// 修改字符集合
		tx.Exec("ALTER TABLE upgrade_terminals MODIFY upgrade_version varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL")
	}
	return nil
}

func (MigrateFunc) Script4() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.Material{})
	tx.Migrator().AutoMigrate(&models.MaterialAuditLog{})
	tx.Migrator().AutoMigrate(&models.MaterialTheme{})
	tx.Migrator().AutoMigrate(&models.MaterialThemeConfig{})
	tx.Migrator().DropColumn(&models.MaterialTheme{}, "belong_device")
	tx.Migrator().AutoMigrate(&models.MaterialThemeTerminals{})
	tx.Exec("alter table `material_theme_terminals` drop index `terminal`")
	tx.Exec("alter table `material_theme_terminals` ADD UNIQUE KEY `terminal` (`theme_id`,`robot_id`,`terminal_type`)")
	tx.Migrator().AutoMigrate(&models.Location{})
	return nil
}

func (MigrateFunc) Script5() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.Location{})                   // 商场数据
	tx.Migrator().DropIndex(&models.UpgradeTerminals{}, "terminal") // 删除旧的索引
	// 增加或优化索引
	tx.Migrator().AutoMigrate(&models.AlarmSetting{})
	tx.Migrator().AutoMigrate(&models.DeviceHeatMap{})
	tx.Migrator().AutoMigrate(&models.Terminal{})
	tx.Migrator().AutoMigrate(&models.UpgradeTerminals{})
	tx.Migrator().AutoMigrate(&models.LocationPoints{})
	return nil
}

func (MigrateFunc) Script6() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.DevEventLog{}) // 上位机异常日志
	tx.Exec("DROP INDEX `robot_id` ON `dev_event_log`")
	tx.Exec("DROP INDEX `created_at` ON `dev_event_log`")
	tx.Migrator().AutoMigrate(&models.DeviceActiveDuration{}) // 增加任务时长和任务里程
	tx.Migrator().AutoMigrate(&models.UpgradeSchedule{})      // 增加自动升级开关
	return nil
}

func (MigrateFunc) Script202311() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.AutoMigrate(&models.TerminalConfig{}, &models.TerminalConfigLog{}, &models.TerminalScreencapLog{})
	db.Migrator().AddColumn(&models.LocationPoints{}, "points_value") // 积分价值
	return nil
}

func (MigrateFunc) Script202312() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.AutoMigrate(&models.Terminal{})             // 增加音量设置字段
	tx.AutoMigrate(&models.TerminalScreencapLog{}) // 增加用户id
	tx.Migrator().AlterColumn(&models.Device{}, "latest_active_time")
	return nil
}

func (MigrateFunc) Script202401() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	// 增加任务运行次数字段
	tx.Migrator().AddColumn(&models.DeviceActiveDuration{}, "task_run_count")
	// 任务记录增加操作人
	tx.Migrator().AddColumn(&models.TaskRecord{}, "user")
	// 位置增加外部导航url（用于跳转第三方小程序等）
	tx.Migrator().AddColumn(&models.Location{}, "nav_url")
	// 升级计划添加添加名称字段
	tx.Migrator().AddColumn(&models.UpgradeSchedule{}, "name")
	// device_log索引
	tx.Exec("ALTER TABLE `device_log` DROP INDEX `robot_id`")
	tx.Exec("ALTER TABLE `device_log` DROP INDEX `idx_createdDate_robotID`")
	tx.Exec("ALTER TABLE `device_log` ADD INDEX `idx_robotID_createdDate`(`robot_id`,`created_date`)")
	// task_record索引
	tx.Exec("ALTER TABLE `task_record` DROP INDEX `robot_id`")
	tx.Exec("ALTER TABLE `task_record` DROP INDEX `robot_task`")
	tx.Exec("ALTER TABLE `task_record` DROP INDEX `idx_createdDate_robotID`")
	tx.Exec("ALTER TABLE `task_record` ADD INDEX `idx_beginTime_robotID`(`begin_time`,`robot_id`)")
	tx.Exec("ALTER TABLE `task_record` ADD INDEX `idx_robotID_createdDate`(`robot_id`,`created_date`)")
	// alarm_notify_record索引
	tx.Exec("ALTER TABLE `alarm_notify_record` DROP INDEX `robot_id`")
	tx.Exec("ALTER TABLE `alarm_notify_record` DROP INDEX `idx_robot_created_date`")
	tx.Exec("ALTER TABLE `alarm_notify_record` ADD INDEX `idx_robotID_createdDate`(`robot_id`,`created_date`)")
	// 设备增加电量
	tx.Migrator().AddColumn(&models.Device{}, "battery")
	// 截图表自动迁移
	tx.AutoMigrate(&models.TerminalScreencapLog{}) // 增加用户id
	return nil
}

// Script20240
func (MigrateFunc) Script202402() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.QuickReply{}) // 新建快捷回复表
	return nil
}

func (MigrateFunc) Script202403() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.Terminal{})                // 新增cpu架构字段
	tx.Migrator().AlterColumn(&models.TerminalConfig{}, "value") // 更新字段长度
	tx.Migrator().AutoMigrate(&models.TerminalConfig{})          // 增加唯一索引
	// 重建version索引
	tx.Migrator().DropIndex(&models.UpgradePackage{}, "version")
	tx.Migrator().AutoMigrate(&models.UpgradePackage{})
	// shell日志
	tx.Migrator().AutoMigrate(&models.WebshellLog{})
	// 更新索引
	tx.Migrator().DropIndex(&models.AlarmSetting{}, "idx_robotid_alarmtype")
	tx.Migrator().AutoMigrate(&models.AlarmSetting{})
	return nil
}

func (MigrateFunc) Script202404() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	// 增加出门时长和回充时长
	tx.Migrator().AutoMigrate(&models.DeviceActiveDuration{})
	tx.Migrator().AutoMigrate(&models.DevicePosition{})
	tx.Migrator().AddColumn(&models.Device{}, "position_id")
	tx.Migrator().AddColumn(&models.TaskRecord{}, "work_type")
	// 身份素材增加字段
	tx.Migrator().AutoMigrate(&models.MaterialTheme{})
	tx.Migrator().AutoMigrate(&models.AlarmSetting{})
	// 素材新表名V2
	tx.Migrator().AutoMigrate(&models.Material{})
	tx.Migrator().AutoMigrate(&models.MaterialFolder{})
	tx.Migrator().AutoMigrate(&models.MaterialTheme{})
	tx.Migrator().AutoMigrate(&models.MaterialAuditLog{})
	tx.Migrator().AutoMigrate(&models.MaterialThemeConfig{})
	tx.Migrator().AutoMigrate(&models.MaterialThemeTerminals{})
	// 本地词库
	tx.Migrator().AutoMigrate(&models.LocalQAAnswer{})
	tx.Migrator().AutoMigrate(&models.LocalQAKeyword{})
	// 位置标签
	tx.Migrator().AutoMigrate(&models.LocalQALib{})
	tx.Migrator().AutoMigrate(&models.LocationTag{})
	tx.Migrator().AutoMigrate(&models.ObjAssociation{})
	// 操作日志
	tx.Migrator().AutoMigrate(&models.OperationLog{})
	return nil
}

func (MigrateFunc) Script202405() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AddColumn(&models.MaterialTheme{}, "created_user")
	tx.Migrator().AutoMigrate(&models.MallService{})
	tx.Migrator().AutoMigrate(&models.DeviceActiveDuration{})
	return nil
}

func (MigrateFunc) Script202407() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Migrator().AutoMigrate(&models.PositionKeywords{})      // 位置点关键字
	tx.Migrator().AutoMigrate(&models.Location{})              // 增加位置坐标
	tx.Migrator().AutoMigrate(&models.MallServiceQA{})         // 商场服务常见问题
	tx.Migrator().AutoMigrate(&models.MallServiceQAKeywords{}) // 商场服务常见问题关键字
	return nil
}

func (MigrateFunc) Script202408() error {
	db := mysql.NewDB()
	tx := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci").Session(&gorm.Session{})
	tx.Exec("ALTER TABLE `upgrade_terminals` DROP INDEX `terminal`")
	tx.Migrator().AutoMigrate(&models.UpgradeTerminals{})
	tx.Migrator().DropIndex(&models.DevEventLog{}, "idx_msg")
	tx.Migrator().CreateIndex(&models.DevEventLog{}, "idx_createdAt_robotID")
	// 分表初始化
	sharding.InitSharding(mysql.NewDB())
	// 去掉告警记录已经不用的字段
	tx.Migrator().DropColumn(&models.AlarmNotifyRecord{}, "robot_direction")
	tx.Migrator().DropColumn(&models.AlarmNotifyRecord{}, "deal_user_name")
	tx.Migrator().DropColumn(&models.AlarmNotifyRecord{}, "is_deal")
	// 优化设备活跃表的索引
	tx.Migrator().DropIndex(&models.DeviceActiveDuration{}, "created_at")
	tx.Migrator().DropIndex(&models.DeviceActiveDuration{}, "robot_date")
	tx.Migrator().AutoMigrate(&models.DeviceActiveDuration{})
	// 优化热力图表的索引
	tx.Migrator().AutoMigrate(&models.DeviceHeatMap{})
	tx.Migrator().DropIndex(&models.DeviceHeatMap{}, "robot_id")
	tx.Migrator().DropIndex(&models.DeviceHeatMap{}, "created_minute")

	tx.Migrator().AutoMigrate(&models.Device{})
	return nil
}
